import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Radio, Space, TimePicker } from 'antd';
import cs from 'classnames';
import dayjs from 'dayjs';

import { store } from '@/store';

import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import {
  proShiftScheduleInfoAdd,
  proShiftScheduleInfoGenerateCalendar,
  proShiftScheduleInfoGet,
  proShiftScheduleInfoUpdate
} from '@/services/bizApi/shengchanpaibanjiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';
import styles from './index.module.scss';
import Personal, { PersonalRef } from './personal';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const shiftSystemGroupArr = [
  {
    label: '六班四倒',
    value: 64
  },
  {
    label: '五班四倒',
    value: 54
  },
  {
    label: '五班三倒',
    value: 53
  },
  {
    label: '四班三倒',
    value: 43
  },
  {
    label: '三班三倒',
    value: 33
  },
  {
    label: '五班两倒',
    value: 52
  },
  {
    label: '四班两倒',
    value: 42
  },
  {
    label: '三班两倒',
    value: 32
  },
  {
    label: '两班两倒',
    value: 22
  }
];

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const personal = useRef<PersonalRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [scheduleBool, setScheduleBool] = useState<boolean>(false);
  const [teamIdListArr, setTeamIdListArr] = useState<number[]>(new Array(6).fill(-1));
  const [shiftIdListArr, setShiftIdListArr] = useState<number[]>(new Array(6).fill(-1));
  const [shortshiftIdListArr, setShortShiftIdListArr] = useState<number[]>([]);
  const [tableData, setTableData] = useState<any[]>([]);
  const [tableData1, setTableData1] = useState<any[]>([]);
  const [tableData2, setTableData2] = useState<any[]>([]);
  const [tableData3, setTableData3] = useState<any[]>([]);
  const [tableData4, setTableData4] = useState<any[]>([]);

  const proShiftTeam = useRequest(
    async () => {
      const res = await proShiftTeamPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const proShiftScheduleInfo = useRequest(
    async (id: string) => {
      const res = await proShiftScheduleInfoGet({ id });
      const data = res?.data;
      const initShiftIdListObj = Object.fromEntries(
        data?.shiftIdList?.map((item, index) => {
          return [`shiftIdList${index + 1}`, item];
        }) || []
      );
      const initTeamIdListObj = Object.fromEntries(
        data?.teamIdList?.map((item, index) => {
          return [`teamIdList${index + 1}`, item];
        }) || []
      );
      setShiftIdListArr([
        ...(data?.shiftIdList || []),
        ...shiftIdListArr.slice(data?.shiftIdList?.length)
      ]);
      setTeamIdListArr([
        ...(data?.teamIdList || []),
        ...teamIdListArr.slice(data?.teamIdList?.length)
      ]);
      setShortShiftIdListArr(
        (data?.shiftIdList || [])?.sort((a, b) => a - b)?.filter((item) => item !== -1)
      );
      // 回填数据
      form.setFieldsValue({
        ...res?.data,
        month: data?.month ? dayjs(data?.month) : undefined,
        ...initShiftIdListObj,
        ...initTeamIdListObj,
        shift1beginTime: data?.shift1beginTime ? dayjs(data?.shift1beginTime) : undefined,
        shift2beginTime: data?.shift2beginTime ? dayjs(data?.shift2beginTime) : undefined,
        shift3beginTime: data?.shift3beginTime ? dayjs(data?.shift3beginTime) : undefined,
        shift4beginTime: data?.shift4beginTime ? dayjs(data?.shift4beginTime) : undefined
      });

      const title = data?.calendarList?.[0]?.map((item) => {
        const arr = item?.shiftDate?.split('-');
        return arr?.[arr?.length - 1] || '-';
      });
      const datas = data?.calendarList?.map((item) => {
        return [
          { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
          ...(item?.slice(0, 7) || [])
        ];
      });
      const datas1 = data?.calendarList?.map((item) => {
        return [
          { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
          ...(item?.slice(7, 14) || [])
        ];
      });
      const datas2 = data?.calendarList?.map((item) => {
        return [
          { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
          ...(item?.slice(14, 21) || [])
        ];
      });
      const datas3 = data?.calendarList?.map((item) => {
        return [
          { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
          ...(item?.slice(21, 28) || [])
        ];
      });
      const datas4 = data?.calendarList?.map((item) => {
        return [
          { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
          ...(item?.slice(28) || [])
        ];
      });
      setTableData([
        ['班次', ...(title?.slice(0, 7) || [])]?.map((item) => {
          return {
            id: item,
            teamName: item,
            disabled: true
          };
        }),
        ...(datas || [])
      ]);
      setTableData1([
        ['班次', ...(title?.slice(7, 14) || [])]?.map((item) => {
          return {
            id: item,
            teamName: item,
            disabled: true
          };
        }),
        ...(datas1 || [])
      ]);
      setTableData2([
        ['班次', ...(title?.slice(14, 21) || [])]?.map((item) => {
          return {
            id: item,
            teamName: item,
            disabled: true
          };
        }),
        ...(datas2 || [])
      ]);
      setTableData3([
        ['班次', ...(title?.slice(21, 28) || [])]?.map((item) => {
          return {
            id: item,
            teamName: item,
            disabled: true
          };
        }),
        ...(datas3 || [])
      ]);
      setTableData4([
        ['班次', ...(title?.slice(28) || [])]?.map((item) => {
          return {
            id: item,
            teamName: item,
            disabled: true
          };
        }),
        ...(datas4 || [])
      ]);

      setScheduleBool(true);
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      let len = 0;
      const query = {
        ...values,
        shift1beginTime: values?.shift1beginTime
          ? dayjs(values?.shift1beginTime).format('HH:mm:ss')
          : undefined,
        shift2beginTime: values?.shift2beginTime
          ? dayjs(values?.shift2beginTime).format('HH:mm:ss')
          : undefined,
        shift3beginTime: values?.shift3beginTime
          ? dayjs(values?.shift3beginTime).format('HH:mm:ss')
          : undefined,
        shift4beginTime: values?.shift4beginTime
          ? dayjs(values?.shift4beginTime).format('HH:mm:ss')
          : undefined,
        month: values?.month ? dayjs(values?.month).format('YYYY-MM') : undefined,
        shiftSystemName: shiftSystemGroupArr?.filter(
          (item) => item.value === values?.shiftSystemId
        )?.[0]?.label
      };
      if (values?.shiftSystemId === 64) {
        len = 6;
      } else if (
        values?.shiftSystemId === 54 ||
        values?.shiftSystemId === 53 ||
        values?.shiftSystemId === 52
      ) {
        len = 5;
      } else if (values?.shiftSystemId === 43 || values?.shiftSystemId === 42) {
        len = 4;
      } else if (values?.shiftSystemId === 33 || values?.shiftSystemId === 32) {
        len = 3;
      } else if (values?.shiftSystemId === 22) {
        len = 2;
      }
      query.teamIdList = teamIdListArr?.slice(0, len);
      query.teamNameList = teamIdListArr
        ?.slice(0, len)
        ?.filter((item) => item > 0)
        ?.map((item) => proShiftTeam?.data?.filter((itm) => itm.id === item)?.[0]?.name);
      const obj = shiftIdListArr
        ?.slice(0, len)
        ?.filter((item) => item > 0)
        .reduce((acc, val) => {
          //@ts-ignore
          acc[val] = (acc[val] || 0) + 1;
          return acc;
        }, {});
      let bool = false;
      Object.keys(obj).forEach((item) => {
        //@ts-ignore
        if (obj?.[item] > 1) {
          bool = true;
        }
      });
      if (bool) {
        store.app?.message.info('早班、中班、晚班、夜班只能选择一次');
        return;
      }
      query.shiftIdList = shiftIdListArr?.slice(0, len);
      query.shiftNameList = shiftIdListArr?.slice(0, len)?.map((item) => {
        if (item === 0) return '休息';
        if (item === 1) return '早班';
        if (item === 2) return '中班';
        if (item === 3) return '晚班';
        if (item === 4) return '夜班';
      });
      if (!scheduleBool) {
        const res = await proShiftScheduleInfoGenerateCalendar(query);
        const title = res?.data?.[0]?.map((item) => {
          const arr = item?.shiftDate?.split('-');
          return arr?.[arr?.length - 1] || '-';
        });
        const datas = res?.data?.map((item) => {
          return [
            { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
            ...(item?.slice(0, 7) || [])
          ];
        });
        const datas1 = res?.data?.map((item) => {
          return [
            { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
            ...(item?.slice(7, 14) || [])
          ];
        });
        const datas2 = res?.data?.map((item) => {
          return [
            { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
            ...(item?.slice(14, 21) || [])
          ];
        });
        const datas3 = res?.data?.map((item) => {
          return [
            { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
            ...(item?.slice(21, 28) || [])
          ];
        });
        const datas4 = res?.data?.map((item) => {
          return [
            { id: item?.[0]?.shiftName, teamName: item?.[0]?.shiftName, disabled: true },
            ...(item?.slice(28) || [])
          ];
        });
        setTableData([
          ['班次', ...(title?.slice(0, 7) || [])]?.map((item) => {
            return {
              id: item,
              teamName: item,
              disabled: true
            };
          }),
          ...(datas || [])
        ]);
        setTableData1([
          ['班次', ...(title?.slice(7, 14) || [])]?.map((item) => {
            return {
              id: item,
              teamName: item,
              disabled: true
            };
          }),
          ...(datas1 || [])
        ]);
        setTableData2([
          ['班次', ...(title?.slice(14, 21) || [])]?.map((item) => {
            return {
              id: item,
              teamName: item,
              disabled: true
            };
          }),
          ...(datas2 || [])
        ]);
        setTableData3([
          ['班次', ...(title?.slice(21, 28) || [])]?.map((item) => {
            return {
              id: item,
              teamName: item,
              disabled: true
            };
          }),
          ...(datas3 || [])
        ]);
        setTableData4([
          ['班次', ...(title?.slice(28) || [])]?.map((item) => {
            return {
              id: item,
              teamName: item,
              disabled: true
            };
          }),
          ...(datas4 || [])
        ]);
        store.app?.message.success('排班日历已生成');

        setScheduleBool(true);
        return;
      }

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? proShiftScheduleInfoUpdate(query)
        : proShiftScheduleInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setScheduleBool(false);
      clear();
      setTableData([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            proShiftScheduleInfo.run(arg?.rowData?.id as unknown as string);
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setScheduleBool(false);
    clear();
    setTableData([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  const clear = () => {
    form.setFieldsValue({
      teamIdList1: undefined,
      teamIdList2: undefined,
      teamIdList3: undefined,
      teamIdList4: undefined,
      teamIdList5: undefined,
      teamIdList6: undefined,
      shiftIdList1: undefined,
      shiftIdList2: undefined,
      shiftIdList3: undefined,
      shiftIdList4: undefined,
      shiftIdList5: undefined,
      shiftIdList6: undefined,
      shift1beginTime: undefined,
      shift2beginTime: undefined,
      shift3beginTime: undefined,
      shift4beginTime: undefined
    });
    setShiftIdListArr(new Array(6).fill(-1));
    setTeamIdListArr(new Array(6).fill(-1));
    setShortShiftIdListArr([]);
  };
  return (
    <Drawer
      title={
        {
          add: '新增排班',
          edit: '编辑排班',
          detail: '排班详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={() => {
                  if (!scheduleBool) {
                    store.app?.message.info('请先生成排班日历');
                    return;
                  }
                  onSave();
                }}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="60%"
      open={open}
      onClose={onCancel}
    >
      <div style={{ padding: '0 20px' }}>
        <Form
          onFinish={onFinish}
          form={form}
          layout="horizontal"
          labelAlign="left"
          labelCol={{ span: 2.5 }}
          wrapperCol={{ span: 14 }}
          requiredMark={args?.type !== 'detail'}
          disabled={args?.type === 'detail'}
          variant={args?.type === 'detail' ? 'borderless' : undefined}
        >
          <Form.Item
            label="排班名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入排班名称'
              }
            ]}
          >
            <Input placeholder="请输入排班名称" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="排班月份"
            name="month"
            rules={[
              {
                required: true,
                message: '请选择排班月份'
              }
            ]}
          >
            <DatePicker
              picker="month"
              placeholder="请选择排班月份"
              style={{ width: '100%' }}
              onChange={() => {
                setScheduleBool(false);
              }}
            />
          </Form.Item>
          <Form.Item
            label="班制"
            name="shiftSystemId"
            rules={[
              {
                required: true,
                message: '请选择班制'
              }
            ]}
          >
            <Radio.Group
              options={shiftSystemGroupArr}
              onChange={(e) => {
                clear();
                setScheduleBool(false);
              }}
            />
          </Form.Item>
          <Form.Item noStyle dependencies={['shiftSystemId']}>
            {({ getFieldValue }) => {
              let len = [];
              const value = getFieldValue('shiftSystemId');
              if (value === 64) {
                len = new Array(6).fill(-1);
              } else if (value === 54 || value === 53 || value === 52) {
                len = new Array(5).fill(-1);
              } else if (value === 43 || value === 42) {
                len = new Array(4).fill(-1);
              } else if (value === 33 || value === 32) {
                len = new Array(3).fill(-1);
              } else if (value === 22) {
                len = new Array(2).fill(-1);
              }
              if (len?.length > 0) {
                return (
                  <>
                    <div style={{ display: 'flex' }}>
                      <div style={{ width: '80px', paddingTop: '6px' }}>
                        <span style={{ color: 'red', paddingRight: '4px' }}>*</span>
                        班组名称:
                      </div>
                      {len?.map((item, index) => {
                        return (
                          <ProFormSelect
                            key={index}
                            name={`teamIdList${index + 1}`}
                            label=""
                            placeholder="请选择班组"
                            rules={[{ required: true, message: '请选择班组' }]}
                            request={async () => {
                              const res = await proShiftTeamPage({ page: 1, size: 1000 });
                              return (
                                res?.data?.records?.map((item) => {
                                  return {
                                    label: item?.name,
                                    value: item?.id
                                  };
                                }) || []
                              );
                            }}
                            onChange={(value: number) => {
                              const arr = teamIdListArr;
                              arr.splice(index, 1, value);
                              setTeamIdListArr(arr);
                              setScheduleBool(false);
                            }}
                            style={{
                              width: '120px'
                            }}
                          />
                        );
                      })}
                    </div>
                    <div style={{ display: 'flex' }}>
                      <div style={{ width: '80px', paddingTop: '6px' }}>
                        <span style={{ color: 'red', paddingRight: '4px' }}>*</span>
                        班次名称:
                      </div>
                      {len?.map((item, index) => {
                        return (
                          <ProFormSelect
                            key={index}
                            name={`shiftIdList${index + 1}`}
                            label=""
                            placeholder="请选择班次"
                            rules={[{ required: true, message: '请选择班次' }]}
                            request={async () => {
                              return [
                                {
                                  label: '早班',
                                  value: 1
                                },
                                {
                                  label: '中班',
                                  value: 2
                                },
                                {
                                  label: '晚班',
                                  value: 3
                                },
                                {
                                  label: '夜班',
                                  value: 4
                                },
                                {
                                  label: '休息',
                                  value: 0
                                }
                              ];
                            }}
                            onChange={(value: number) => {
                              const arr = shiftIdListArr;
                              arr.splice(index, 1, value);
                              setShortShiftIdListArr(
                                [...new Set(arr)]
                                  ?.sort((a, b) => a - b)
                                  ?.filter((item) => item !== -1)
                              );
                              setShiftIdListArr(arr);
                              setScheduleBool(false);
                            }}
                            style={{
                              width: '120px'
                            }}
                          />
                        );
                      })}
                    </div>
                  </>
                );
              }
              return null;
            }}
          </Form.Item>
          {shortshiftIdListArr?.map((item, index) => {
            if (item === 1) {
              return (
                <Form.Item
                  key={index}
                  label="早班时间"
                  name="shift1beginTime"
                  rules={[
                    {
                      required: true,
                      message: '请选择早班时间'
                    }
                  ]}
                >
                  <TimePicker
                    onChange={() => {
                      setScheduleBool(false);
                    }}
                  />
                </Form.Item>
              );
            }
            if (item === 2) {
              return (
                <Form.Item
                  key={index}
                  label="中班时间"
                  name="shift2beginTime"
                  rules={[
                    {
                      required: true,
                      message: '请选择中班时间'
                    }
                  ]}
                >
                  <TimePicker
                    onChange={() => {
                      setScheduleBool(false);
                    }}
                  />
                </Form.Item>
              );
            }
            if (item === 3) {
              return (
                <Form.Item
                  key={index}
                  label="晚班时间"
                  name="shift3beginTime"
                  rules={[
                    {
                      required: true,
                      message: '请选择晚班时间'
                    }
                  ]}
                >
                  <TimePicker
                    onChange={() => {
                      setScheduleBool(false);
                    }}
                  />
                </Form.Item>
              );
            }
            if (item === 4) {
              return (
                <Form.Item
                  key={index}
                  label="夜班时间"
                  name="shift4beginTime"
                  rules={[
                    {
                      required: true,
                      message: '请选择夜班时间'
                    }
                  ]}
                >
                  <TimePicker
                    onChange={() => {
                      setScheduleBool(false);
                    }}
                  />
                </Form.Item>
              );
            }
            return null;
          })}
        </Form>
        <div style={{ marginBottom: '30px' }}>
          <Button
            type="primary"
            disabled={args?.type === 'detail' || submit.loading}
            loading={submit.loading}
            onClick={() => {
              setScheduleBool(false);
              onSave();
            }}
          >
            生成日历
          </Button>
        </div>
        {scheduleBool && (
          <>
            <div className={styles['table']}>
              {tableData?.map((item, index) => {
                return (
                  <div key={index} className={styles['item']}>
                    {item?.map(
                      (
                        itm: { teamName: string; shiftName?: string; disabled?: boolean },
                        idx: number
                      ) => {
                        return (
                          <div
                            key={idx}
                            className={cs(styles['item-value'], {
                              [styles['item-value-blue']]: itm?.shiftName
                            })}
                            onClick={() => {
                              if (itm?.disabled) return;
                              personal.current?.open({
                                rowData: itm
                              });
                            }}
                          >
                            {itm?.teamName}
                          </div>
                        );
                      }
                    )}
                  </div>
                );
              })}
            </div>
            <div className={styles['table']}>
              {tableData1?.map((item, index) => {
                return (
                  <div key={index} className={styles['item']}>
                    {item?.map(
                      (
                        itm: { teamName: string; shiftName?: string; disabled?: boolean },
                        idx: number
                      ) => {
                        return (
                          <div
                            key={idx}
                            className={cs(styles['item-value'], {
                              [styles['item-value-blue']]: itm?.shiftName
                            })}
                            onClick={() => {
                              if (itm?.disabled) return;
                              personal.current?.open({
                                rowData: itm
                              });
                            }}
                          >
                            {itm?.teamName}
                          </div>
                        );
                      }
                    )}
                  </div>
                );
              })}
            </div>
            <div className={styles['table']}>
              {tableData2?.map((item, index) => {
                return (
                  <div key={index} className={styles['item']}>
                    {item?.map(
                      (
                        itm: { teamName: string; shiftName?: string; disabled?: boolean },
                        idx: number
                      ) => {
                        return (
                          <div
                            key={idx}
                            className={cs(styles['item-value'], {
                              [styles['item-value-blue']]: itm?.shiftName
                            })}
                            onClick={() => {
                              if (itm?.disabled) return;
                              personal.current?.open({
                                rowData: itm
                              });
                            }}
                          >
                            {itm?.teamName}
                          </div>
                        );
                      }
                    )}
                  </div>
                );
              })}
            </div>
            <div className={styles['table']}>
              {tableData3?.map((item, index) => {
                return (
                  <div key={index} className={styles['item']}>
                    {item?.map(
                      (
                        itm: { teamName: string; shiftName?: string; disabled?: boolean },
                        idx: number
                      ) => {
                        return (
                          <div
                            key={idx}
                            className={cs(styles['item-value'], {
                              [styles['item-value-blue']]: itm?.shiftName
                            })}
                            onClick={() => {
                              if (itm?.disabled) return;
                              personal.current?.open({
                                rowData: itm
                              });
                            }}
                          >
                            {itm?.teamName}
                          </div>
                        );
                      }
                    )}
                  </div>
                );
              })}
            </div>
            <div className={styles['table']}>
              {tableData4?.map((item, index) => {
                return (
                  <div key={index} className={styles['item']}>
                    {item?.map(
                      (
                        itm: { teamName: string; shiftName?: string; disabled?: boolean },
                        idx: number
                      ) => {
                        return (
                          <div
                            key={idx}
                            className={cs(styles['item-value'], {
                              [styles['item-value-blue']]: itm?.shiftName
                            })}
                            onClick={() => {
                              if (itm?.disabled) return;
                              personal.current?.open({
                                rowData: itm
                              });
                            }}
                          >
                            {itm?.teamName}
                          </div>
                        );
                      }
                    )}
                  </div>
                );
              })}
            </div>
          </>
        )}
      </div>
      <Personal ref={personal} />
    </Drawer>
  );
};

export default forwardRef(Edit);
